package com.easyselection.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.easyselection.dto.Result;
import com.easyselection.entity.SeckillVoucher;
import com.easyselection.entity.VoucherOrder;
import com.easyselection.mapper.VoucherOrderMapper;
import com.easyselection.service.ISeckillVoucherService;
import com.easyselection.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easyselection.utils.RedisIdWorker;
import com.easyselection.utils.UserHolder;
import io.lettuce.core.XReadArgs;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private IVoucherOrderService iVoucherOrderService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        //设置lua脚本的位置
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        //确定返回值
        SECKILL_SCRIPT.setResultType(Long.class);
    }


    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    /**
     * 消息队列版本获取订单信息
     */
    private class VoucherOrderHandler implements Runnable{
        String queueName = "stream.orders";
        @Override
        public void run() {
            while(true){
                try {
                    //1.获取消息队列中的订单信息
                    //xreadgroup GROUP group1 consumer1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                    //'>' 表示 从下一个未消费的消息开始读取
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("group1", "consumer1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    //2.判断消息获取是否成功
                    if (list == null || list.isEmpty()){
                        //获取失败, 进行下一次循环, 继续获取
                        continue;
                    }
                    //3.获取成功, 解析消息中的订单信息
                    MapRecord<String, Object, Object> mapRecord = list.get(0);
                    Map<Object, Object> values = mapRecord.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), false);
                    //4. 处理订单
                    handleVoucherOrder(voucherOrder);
                    //5.进行ack确认消息 xack key group id
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "group1", mapRecord.getId());
                } catch (Exception e) {
                    log.error("处理订单异常!", e);
                    //处理异常消息
                    handlePendingList();
                }
            }
        }

        private void handlePendingList() {

            while(true){
                try {
                    //1.获取pending-list中的异常信息
                    //xreadgroup GROUP group1 consumer1 COUNT 1 BLOCK 2000 STREAMS streams.order 0
                    //'0' 表示 从pending-list中第一个消息开始读取
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("group1", "consumer1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    //2.判断消息获取是否成功
                    if (list == null || list.isEmpty()){
                        //获取失败, 说明pending-list中获取不到异常消息, 结束循环
                        break;
                    }
                    //3.获取成功, 解析消息中的订单信息
                    MapRecord<String, Object, Object> mapRecord = list.get(0);
                    Map<Object, Object> values = mapRecord.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), false);
                    //4. 处理订单
                    handleVoucherOrder(voucherOrder);
                    //5.进行ack确认消息 xack key group id
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "group1", mapRecord.getId());
                } catch (Exception e) {
                    log.error("处理pending-list订单异常!", e);
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }

//    /**
//     * 阻塞队列版本获取订单信息
//     */
//    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
//    private class VoucherOrderHandler implements Runnable{
//        @Override
//        public void run() {
//            while(true){
//                try {
//                    //1.获取阻塞队列中的订单信息
//                    VoucherOrder voucherOrder = orderTasks.take();
//                    //2. 处理订单
//                    handleVoucherOrder(voucherOrder);
//                } catch (Exception e) {
//                    log.error("处理订单异常!", e);
//                }
//            }
//        }
//    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        //1.获取用户
        Long userId = voucherOrder.getUserId();

        //使用Redisson分布式锁
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //获取锁 不加参数表示默认不重试, 超时释放时间为30s
        boolean isLock = lock.tryLock();

        //判断获取锁是否成功
        if (!isLock) {
            //获取锁失败
            log.error("不允许重复下单操作!");
        }
        try {
            //通过主线程拿到代理对象proxy
            proxy.createVoucherOrderAsync(voucherOrder);
        } finally {
            //释放锁
            lock.unlock();
        }
    }

    @Transactional
    public void createVoucherOrderAsync(VoucherOrder voucherOrder) {
        //5.一人一单
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        //查询订单
        int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        //判断订单是否存在
        if(count > 0) {
            log.error("您已经购买过了!");
            return;
        }
        //6. 扣减库存
        boolean success = seckillVoucherService.update().
                setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0).update();

        if(!success){
            //扣减失败
            log.error("库存不足!");
            return;
        }
        //将订单保存到数据库
        save(voucherOrder);
    }

    private IVoucherOrderService proxy;


    /**
     * 异步秒杀优化: 改造seckillVoucher代码
     * Redis stream类型消息队列版本
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucherAsync(Long voucherId) {
        //1.执行lua脚本
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        //订单id
        long orderId = redisIdWorker.nextId("order");

        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                String.valueOf(orderId)
        );

        //2.判断脚本结果是否为0
        int ret = result.intValue();
        if(ret != 0){
            //2.1 不为0没有购买资格 返回异常信息
            return Result.fail(ret == 1 ? "库存不足!" : "请勿重复下单!");
        }
        //2.2 为0有购买资格 使用消息队列处理下单逻辑

        //2.7 获取代理对象
        proxy = (IVoucherOrderService)AopContext.currentProxy();
        //3.返回订单id
        return Result.ok(orderId);
    }


//    /**
//     * 异步秒杀优化: 改造seckillVoucher代码
//     * Java阻塞队列版本
//     * @param voucherId
//     * @return
//     */
//    @Override
//    public Result seckillVoucherAsync(Long voucherId) {
//        //1.执行lua脚本
//        Long userId = UserHolder.getUser().getId();
//        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT,
//                Collections.emptyList(),
//                voucherId.toString(),
//                userId.toString()
//        );
//
//        //2.判断脚本结果是否为0
//        int ret = result.intValue();
//        if(ret != 0){
//            //2.1 不为0没有购买资格 返回异常信息
//            return Result.fail(ret == 1 ? "库存不足!" : "请勿重复下单!");
//        }
//        //2.2 为0有购买资格 把下单信息保存到阻塞队列中
//
//        //2.3 创建订单
//        VoucherOrder voucherOrder = new VoucherOrder();
//        //2.4 订单id
//        long orderId = redisIdWorker.nextId("order");
//        voucherOrder.setId(orderId);
//        voucherOrder.setUserId(userId);
//        //2.5 代金券id
//        voucherOrder.setVoucherId(voucherId);
//        //2.6 加入到阻塞队列
//        orderTasks.add(voucherOrder);
//        //2.7 获取代理对象
//        proxy = (IVoucherOrderService)AopContext.currentProxy();
//        //3.返回订单id
//        return Result.ok(orderId);
//    }


    @Override
    public Result seckillVoucher(Long voucherId) {
        //1.查询优惠券
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        //2.判断秒杀活动是否开始
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀活动尚未开始!");
        }
        //3. 判断秒杀活动是否结束
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("秒杀活动已结束!");
        }

        //4. 判断库存是否充足
        if (voucher.getStock() < 1) {
            return Result.fail("库存不足!");
        }

        Long userId = UserHolder.getUser().getId();

        //使用Redis自定义分布式锁解决集群环境下多进程不可见问题
        //SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
        //获取锁
        //boolean isLock = lock.tryLock(1200L);

        //使用Redisson分布式锁
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //获取锁 不加参数表示默认不重试, 超时释放时间为30s
        boolean isLock = lock.tryLock();

        //判断获取锁是否成功
        if (!isLock) {
            //获取锁失败
            return Result.fail("不允许重复下单操作!");
        }
        try {
            //获取代理对象
            IVoucherOrderService proxy = (IVoucherOrderService)AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } finally {
            //释放锁
            lock.unlock();
        }


//        synchronized (userId.toString().intern()) {
//            //直接调用createVoucherOrder方法, 那么修饰createVoucherOrder方法的Transactional注解会失效,
//            //因为此时调用的是当前类对象调用当前createVoucherOrder方法, 而不是AOP代理对象
//
//            //解决方法①: 注入iVoucherOrderService接口再调用createVoucherOrder方法
//            //return iVoucherOrderService.createVoucherOrder(voucherId);
//
//            //解决方法②: 通过AopContext.currentProxy() 获取代理对象IVoucherOrderService
//            IVoucherOrderService proxy = (IVoucherOrderService)AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        }
    }

    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        //5.一人一单
        Long userId = UserHolder.getUser().getId();

        int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        //判断订单是否存在
        if(count > 0) return Result.fail("您已经购买过了!");

        //6. 扣减库存
        boolean success = seckillVoucherService.update().
                setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0).update();

        if(!success){
            //扣减失败
            return Result.fail("库存不足!");
        }

        //7. 创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        //7.1 订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        //7.3 代金券id
        voucherOrder.setVoucherId(voucherId);
        //将订单保存到数据库
        save(voucherOrder);

        //7.4返回订单id
        return Result.ok(orderId);

    }


}
